from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User,Goods,Comment,UserFollow,User_Exam,Flow_Exam,Goods_Exam
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#导入序列化对象
from myapp.myser import UserSer,GoodsSer,CommentSer

from pymongo import  MongoClient

mongocli = MongoClient(host='localhost',port=27017)

#导入bson
from bson import json_util as jsonb

#定义地址和端口
host = '127.0.0.1'
port = 6379

#建立redis连接
r = redis.Redis(host=host,port=port)

#sql查询结果集美化方法
def dictfetchall(cursor):
    #获取游标描述
    desc = cursor.description
    return [
        dict(zip(  [col[0] for col in desc ],row ))
        for row in cursor.fetchall()
    ]

#商品被多少人关注(包含取关）
class GoodFollow_Exam(APIView):
    def get(self,request):
        gid = request.GET.get("gid")
        uid = request.GET.get("uid")
        #查看是否关注，默认未关注
        type = request.GET.get('type',1)

        #判断关注时间间隔
        if r.get("gz") :
            # print(r.get('gz'))
            return Response({'message':'3分钟之内仅可操作一次！','code':403})

        resp = {}
        if int(type)==1:
            #关注
            userfollow = Flow_Exam(gid = int(gid),uid=int(uid))
            try:
                userfollow.save()
                resp['message'] = '关注成功'
                #同步数据库goods_exam中的flow数
                goods_exam = Goods_Exam.objects.filter(id=int(gid)).first()
                goods_exam.flow = goods_exam.flow +1
                goods_exam.save()
                resp['code'] = 200
                resp['type'] = 0
                # 设置过期时间
                r.set("gz", 1)
                r.expire('gz', 180)
            except Exception as e:
                print(e)
                resp['message'] = '不能重复关注'
                resp['code'] = 403
        else:
            #取关
            #首先查询是否关注
            userfollow = Flow_Exam.objects.filter(gid=int(gid), uid=int(uid))
            if userfollow:
                Flow_Exam.objects.filter(gid=int(gid),uid=int(uid)).delete()
                resp['message'] = '取关成功'
                # 同步数据库goods_exam中的flow数
                goods_exam = Goods_Exam.objects.filter(id=int(gid)).first()
                goods_exam.flow -= 1
                goods_exam.save()
                resp['code'] = 200
                resp['type'] = 1
                r.set("gz", 1)
                # 设置过期时间
                r.expire('gz', 180)
            else:
                resp['message'] = "错误操作！"
                resp['code'] = 405

        return Response(resp)



#商品关注（查询用户关注过的商品列表）
class UidFollow_Exam(View):
    def get(self,request):
        uid = request.GET.get("uid")
        #建立游标对象
        cursor = connection.cursor()
        #执行sql语句
        cursor.execute('SELECT a.id,a.name,a.create_time FROM goods_exam a left join userfollow b on a.id=b.gid  where uid=%s'%str(uid))
        result = dictfetchall(cursor)
        #返回结果
        return HttpResponse(json.dumps(result,ensure_ascii=False,indent=4,default=str),content_type='application/json')